<template>
    <a-layout>
        <!-- 客服列表（房间） -->
        <a-layout-sider width="250" style="background-color: #fff; overflow: auto;height: 588px">
            <a-menu :default-selected-keys="['1']" @select="handleKefuSelect">
                <a-menu-item v-for="item in kefuList" :key="item.id">
                    {{ item.name }}
                </a-menu-item>
            </a-menu>
        </a-layout-sider>

        <!-- 消息内容 -->
        <a-layout-content style="background-color: #fff; overflow: auto;">
            <a-card title="消息内容" style="overflow: auto;height: 508px" id="messageCard">
                <a-watermark content="天工云饰">
                    <a-list :data-source="getMessagesForCurrentKefu">
                        <template #renderItem="{ item }">
                            <a-list-item style="border: 0px solid #fff;">
                                <div :class="{ 'kefu-side': item.type === 'kefu', 'user-side': item.type === 'user' }">
                                    <span
                                        :class="{ 'kefu-label': item.type === 'kefu', 'user-label': item.type === 'user' }">{{
                                            item.type === 'kefu' ? '客服：' : '我：'
                                        }}</span>
                                    <div
                                        :class="{ 'kefu-bubble': item.type === 'kefu', 'user-bubble': item.type === 'user' }">
                                        <template v-if="item.imageUrl">
                                            <a-image :src="item.imageUrl" alt="图片消息"
                                                style="max-width: 100%; max-height: 200px;" @click="toggleFullscreen" />
                                        </template>
                                        <template v-else-if="item.videoUrl">
                                            <video controls :src="item.videoUrl"
                                                style="max-width: 100%; max-height: 200px;" />
                                        </template>
                                        <template v-else-if="item.zipUrl">
                                            <a :href="item.zipUrl" target="_blank">[zip]点击下载</a>
                                        </template>
                                        <template v-else>
                                            {{ item.content }}
                                        </template>
                                    </div>
                                </div>
                            </a-list-item>
                        </template>
                    </a-list>
                </a-watermark>
            </a-card>
            <!-- 上传附件发送消息 -->
            <a-upload :customRequest="handleUploadImg" :fileList="fileList" :beforeUpload="beforeUpload" multiple
                accept="image/*" style="display: inline-block; margin-right: 8px;">
                <a-button>
                    <UploadOutlined /> 上传图片
                </a-button>
            </a-upload>
            <a-upload :customRequest="handleUploadVideo" :fileList="fileList" :beforeUpload="beforeUpload" multiple
                accept=".mp4" style="display: inline-block; margin-right: 8px;">
                <a-button>
                    <UploadOutlined /> 上传视频
                </a-button>
            </a-upload>
            <a-upload :customRequest="handleUploadZip" :fileList="fileList" :beforeUpload="beforeUpload" multiple
                accept=".zip" style="display: inline-block; margin-right: 8px;">
                <a-button>
                    <UploadOutlined /> 上传zip
                </a-button>
            </a-upload>
            <a-input-search placeholder="输入消息" enter-button="发送" @search="sendMessage" style="margin-top: 16px"
                v-model:value="inputValue" />

        </a-layout-content>
    </a-layout>
</template>

<script setup>
import { ref, computed, onMounted, onUpdated, nextTick } from 'vue';

const inputValue = ref('');

const scrollToBottom = () => {
    nextTick(() => {
        const container = document.querySelector('#messageCard');
        container.scrollTo({ top: container.scrollHeight, behavior: 'smooth' })
        setTimeout(() => {
            container.scrollTo({ top: container.scrollHeight, behavior: 'smooth' })    
        }, 500);
        setTimeout(() => {
            container.scrollTo({ top: container.scrollHeight, behavior: 'smooth' })    
        }, 2000);//图片显示获取有延迟，再滚动两次
    });
};

onUpdated(() => {
    scrollToBottom();
});

const kefuList = ref([
    { id: 1, name: '平台客服-ai' },
    { id: 2, name: '店铺客服' },
    { id: 3, name: '你在未来等我吗店铺-客服小i' },
]);

const messages = ref([
    { kefuId: 1, type: 'kefu', content: '您好，有什么可以帮助您的吗？' },
    { kefuId: 2, type: 'kefu', content: '欢迎光临！' },
]);

const currentKefuId = ref(null); // 存储当前选中的客服ID

const getMessagesForCurrentKefu = computed(() => {
    if (!currentKefuId.value) return [];
    return messages.value.filter(msg => msg.kefuId === currentKefuId.value);
});

const handleKefuSelect = (e) => {
    currentKefuId.value = e.key; // 更新当前选中的客服ID
    console.log(currentKefuId.value);
    // 重新计算 getMessagesForCurrentKefu
    getMessagesForCurrentKefu.value = getMessagesForCurrentKefu.value;
};

const messagesForCurrentKefu = computed(() => {
    return messages.value.filter(msg => msg.kefuId === currentKefuId.value).map(msg => msg.content);
});

const sendMessage = (value) => {
    if (value && currentKefuId.value) {
        // 发送消息时，添加当前选中的客服ID
        messages.value.push({ kefuId: currentKefuId.value, type: 'user', content: value });
        // 清空输入框
        inputValue.value = '';
        scrollToBottom();
    }
    if (currentKefuId.value === 1 && !value.startsWith('画')) {
        const messageContent = messagesForCurrentKefu.value
        //console.log(messageContent);
        fetch('/api/ai/dialogue', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ messages: messageContent })
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`Network response was not ok ${response.statusText}`);
                }
                return response.json();
            })
            .then(data => {
                console.log(data);
                messages.value.push({
                    kefuId: currentKefuId.value,
                    type: 'kefu',
                    content: data.message,
                });
                scrollToBottom();
            })
    }
    else if(currentKefuId.value === 1) {
        var task_id = '';
        fetch('/api/ai/imagetask', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ prompt: value })
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`Network response was not ok ${response.statusText}`);
                }
                return response.json();
            })
            .then(data => {
                task_id = data.task_id;
                messages.value.push({
                    kefuId: currentKefuId.value,
                    type: 'kefu',
                    content: "图片生成中，请稍等10~30s...",
                });
                setTimeout(() => {
                    getimage(task_id);
                }, 8000);
                scrollToBottom();
            })
    }
    if (currentKefuId.value === 2) {
        fetch('http://121.36.250.46:5600/generate_recipe', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ message: value })
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`Network response was not ok ${response.statusText}`);
                }
                return response.json();
            })
            .then(data => {
                console.log(data);
                messages.value.push({
                    kefuId: currentKefuId.value,
                    type: 'kefu',
                    content: data.recipe,
                });
                scrollToBottom();
            })
    }
};
function getimage(task_id) {
    fetch('/api/ai/image', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ task_id: task_id })
    })
        .then(response => {
            if (!response.ok) {
                throw new Error(`Network response was not ok ${response.statusText}`);
            }
            return response.json();
        })
        .then(data => {
            messages.value.push({
                kefuId: currentKefuId.value,
                type: 'kefu',
                content: '',
                imageUrl: data.imgUrl,
            });
        })
    scrollToBottom();
}

import { UploadOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { useCustomerStore } from '../stores/customer.js';
const fileList = ref([]); // 存储上传的文件列表
const customerStore = useCustomerStore();

const handleUploadImg = async (options) => {
    const { file } = options;
    // 这里可以添加上传文件的逻辑，例如使用 FormData 发送到后端
    console.log('上传文件:', file);

    // 模拟上传成功后，将文件添加到消息列表中
    if (file) {
        // 假设上传成功后返回了一个 URL
        const fileUrl = URL.createObjectURL(file);
        messages.value.push({
            kefuId: currentKefuId.value,
            type: 'user',
            content: '',
            imageUrl: fileUrl
        });
        scrollToBottom();
    }
};

const handleUploadVideo = async (options) => {
    const { file } = options;
    // 这里可以添加上传文件的逻辑，例如使用 FormData 发送到后端
    console.log('上传文件:', file);

    // 模拟上传成功后，将文件添加到消息列表中
    if (file) {
        // 假设上传成功后返回了一个 URL
        const fileUrl = URL.createObjectURL(file);
        messages.value.push({
            kefuId: currentKefuId.value,
            type: 'user',
            content: '',
            videoUrl: fileUrl
        });
        scrollToBottom();
    }
};

const handleUploadZip = async (options) => {
    const { file } = options;
    // 这里可以添加上传文件的逻辑，例如使用 FormData 发送到后端
    console.log('上传文件:', file);

    // 模拟上传成功后，将文件添加到消息列表中
    if (file) {
        // 假设上传成功后返回了一个 URL
        const fileUrl = URL.createObjectURL(file);
        messages.value.push({
            kefuId: currentKefuId.value,
            type: 'user',
            content: '',
            zipUrl: fileUrl
        });
        scrollToBottom();
    }
};

const beforeUpload = (file) => {
    // 这里可以添加文件验证逻辑，例如文件类型、大小限制等
    console.log('beforeUpload:', file);
    return true; // 返回 true 允许上传，返回 false 阻止上传
};

onMounted(() => {
    // 初始化时，默认选中第一个客服
    currentKefuId.value = kefuList.value[0].id;
    if (customerStore.getLastCustomer) {
        console.log(customerStore.getLastCustomer)
        kefuList.value.push({ id: customerStore.getLastCustomer.id, name: customerStore.getLastCustomer.name });
    }
});

</script>

<style scoped>
.message-row {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    margin-bottom: 8px;
}

.kefu-side {
    display: flex;
    align-items: center;
    justify-content: flex-start;
}

.user-side {
    display: flex;
    align-items: center;
    justify-content: flex-end;
}

.kefu-bubble {
    background-color: #e6f4ff;
    border-radius: 10px;
    padding: 8px 12px;
    margin: 4px 0;
    display: inline-block;
    text-align: left;
    word-wrap: break-word;
}

.user-bubble {
    background-color: #e9fddd;
    border-radius: 10px;
    padding: 8px 12px;
    margin: 4px 0;
    display: inline-block;
    text-align: left;
    word-wrap: break-word;
}

.kefu-label {
    font-weight: bold;
    margin-right: 8px;
}

.user-label {
    font-weight: bold;
    margin-left: 8px;
}

.ant-list .ant-list-item {
    display: inline;
}
</style>